package com.jianyun.jyzs.activity.newsign;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.NewSignReslut;
import com.jianyun.jyzs.bean.SignNewReslut;
import com.jianyun.jyzs.bean.SignRange;
import com.jianyun.jyzs.bean.SignStateBean;
import com.jianyun.jyzs.bean.WillSignBean;
import com.jianyun.jyzs.presenter.NewSignPresenter;
import com.jianyun.jyzs.utils.DateTime;
import com.jianyun.jyzs.utils.DateUtils;
import com.jianyun.jyzs.utils.DeviceUtils;
import com.jianyun.jyzs.utils.LocationManager;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.NetUtil;
import com.jianyun.jyzs.utils.TextUtil;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.INewSignView;
import com.jrmf360.rylib.common.util.ToastUtil;
import com.longsh.optionframelibrary.OptionMaterialDialog;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 新打卡界面
 * Created by yangshijun on 2018/6/6.
 */

public class NewSignActivity extends MvpActivity<INewSignView, NewSignPresenter> implements
        INewSignView, LocationManager.LocationManagerListener, AMap.InfoWindowAdapter, LocationSource {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.iv_calendar)
    ImageView ivCalendar;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.top_rl)
    RelativeLayout topRl;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_fanwei)
    TextView tvFanwei;
    @BindView(R.id.ll_layout)
    LinearLayout llLayout;
    @BindView(R.id.prograssBar)
    ProgressBar prograssBar;
    @BindView(R.id.frmelayout)
    FrameLayout frmelayout;
    @BindView(R.id.img_loading)
    ImageView imgLoading;
    @BindView(R.id.tv_longing)
    TextView tvLonging;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.rl_layout)
    RelativeLayout rlLayout;
    @BindView(R.id.ll_location_refresh)
    LinearLayout llLocationRefresh;
    @BindView(R.id.tv_Tishi)
    TextView tvTishi;

    private AMap aMap;
    private LocationManager locationManager;
    private AMapLocation aMapLocation;
    private LatLng latlng;//定点位置
    private LatLng latitude2;//当前位置
    private MyLocationStyle myLocationStyle;
    private MarkerOptions markerOption;
    private Marker marker;

    private View infowindow;
    private UiSettings mUiSettings;
    private MarkerOptions markerOption2;
    // //latitude=30.467302#longitude=114.416814

    private Marker marker2;
    private Message message;
    private String enterpriseCode;
    private String userId;
    private String label;
    private String[] NETTYPE = {"定位失败", "GPRS", "前次定位结果", "缓存定位结果", "Wifi", "EDGE", "离线定位结果"};//网络类型
    private String signTypes;
    private String timeFormat = "HH:mm";
    private OptionMaterialDialog mMaterialDialog;
    private boolean isclick = false;
    private boolean isInit = true;//是否初次开始定位
    private WillSignBean willSignBean;
    private static final int msgKey1 = 1;
    private TimeThread timeThread;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_sign);
        UtilsStyle.setStatusBarMode(this,true);
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        getPresenter().getNowSignDetail(enterpriseCode, userId);
        //top1 获取当前经纬度
        if (locationManager == null) {
            locationManager = new LocationManager(this);
        }
        //locationManager.locationStart(this);
        initView();
        //设置两个都不能点击
        llLocationRefresh.setEnabled(false);
        frmelayout.setEnabled(false);
        timeThread = new TimeThread();
        timeThread.start();

    }

    private void initView() {

        if (aMap == null) {
            aMap = mapView.getMap();

        }
        //初始化定位
        //mlocationClient = new AMapLocationClient(getApplicationContext());
        //初始化AMapLocationClientOption对象
        //mLocationOption = new AMapLocationClientOption();
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        //  myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点，用于满足只想使用定位，不想使用定位小蓝点的场景，设置false以后图面上不再有定位蓝点的概念，但是会持续回调位置信息。
        // aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        // aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        //UiSettings uiSettings = aMap.getUiSettings();
        //uiSettings.setCompassEnabled(true);//指南针
        //uiSettings.setScaleControlsEnabled(true);//比例尺
        //uiSettings.setMyLocationButtonEnabled(true);//定位角标
        // 缩放级别（zoom）：地图缩放级别范围为【4-20级】，值越大地图越详细
        aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
        //设置中心点
        //aMap.moveCamera(CameraUpdateFactory.changeLatLng(latlng));
        // 设置定位监听
        aMap.setLocationSource(this);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.MAP_TYPE_SATELLITE);
        aMap.setInfoWindowAdapter(this);
        mUiSettings = aMap.getUiSettings();

        mUiSettings.setZoomGesturesEnabled(false);// 禁止通过手势缩放地图
        mUiSettings.setScrollGesturesEnabled(false);// 禁止通过手势移动地图

        frmelayout.setEnabled(false);

    }

    int i = 1;

    private void addMarkersToMap() {
        if (marker2 != null) {
            marker2.remove();
        }

        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latlng));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
        Log.i("test","la2:"+latitude2.toString()+"\n"+"la:"+latlng.toString());

        markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .fromBitmap(BitmapFactory
                        .decodeResource(getResources(), R.drawable.icon_location)))
                .position(latitude2)
                .draggable(true);

        markerOption2 = new MarkerOptions().icon(BitmapDescriptorFactory
                //.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                .fromBitmap(BitmapFactory
                        .decodeResource(getResources(), R.drawable.icon_location_5)))
                .title("")
                .snippet("详细信息")
                .position(latlng)
                .draggable(true);

        marker = aMap.addMarker(markerOption);
        marker2 = aMap.addMarker(markerOption2);
        marker2.showInfoWindow();
    }


    @OnClick({R.id.topBack, R.id.iv_calendar, R.id.frmelayout, R.id.ll_location_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.iv_calendar:
                startActivity(new Intent(this, NewSignReCordActivity.class));
                finish();
                break;
            case R.id.frmelayout:

                //获取打卡状态
                if (willSignBean.isCanSign()) {
                    isclick = true;
                    getPresenter().getUserSignState(enterpriseCode, userId, signTypes);
                } else {
                    ToastUtil.showToast(this, willSignBean.getMessage());
                }
                break;
            case R.id.ll_location_refresh:
                //刷新定位
                Log.i("test", "刷新定位");
                locationManager.locationStart(this);

                break;

        }
    }

    public HashMap<String, String> signPamars() {
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "Sign");
        map.put("enterpriseCode", enterpriseCode);
        map.put("employeeId", userId);
        String LOCATION_X = aMapLocation.getLongitude() + "";
        String LOCATION_Y = aMapLocation.getLatitude() + "";
        map.put("location_X", LOCATION_X);
        map.put("location_Y", LOCATION_Y);
        map.put("scale", "5");
        label = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet();
        map.put("label", label);
        String deviceId = DeviceUtils.getAndroidID(this);
        map.put("deviceId", deviceId);
        map.put("netType", NETTYPE[aMapLocation.getLocationType()]);
        map.put("platFormInfo", "android");
        map.put("userIp", NetUtil.getLocalIpAddress());
        map.put("sourceSystem", "jyzs");
        //打卡类型
        map.put("signType", signTypes);
        map.put("workTime",willSignBean.getWorkTime());
        String bcDate = DateTime.yyyy_MM_dd();
        map.put("bcDate",bcDate);
        return map;
    }

    /**
     * 定位结果
     *
     * @param result
     * @param aMapLocation
     */
    @Override
    public void locationResult(boolean result, AMapLocation aMapLocation) {
        Log.i("test", "已经定位");//lat/lng: (30.499685,114.407707)
        if (result) {
            llLocationRefresh.setEnabled(false);
            this.aMapLocation = aMapLocation;
            double latitude = aMapLocation.getLatitude();
            double longitude = aMapLocation.getLongitude();
            latlng = new LatLng(latitude, longitude);
            Log.i("test", "定位：" + latlng.toString() + "\n" + aMapLocation.toString());
            getPresenter().judegLoactionRange(enterpriseCode, latitude + "", longitude + "");

        } else {
            llLocationRefresh.setEnabled(true);
            //定位失败 重新定位
            imgLoading.setImageResource(R.drawable.icon_location_loading_2);
            tvLonging.setText("定位失败，点击刷新");

        }
    }


    @Override
    public void onRangeReslut(SignRange signRange) {
        //signPamars();
        //是否在考勤范围内
        if (signRange.isRangeAddress()) {
            if (TextUtils.isEmpty(tvFanwei.getText())) {
                //设置不可以点击
                frmelayout.setEnabled(true);
                isclick = false;
                frmelayout.setSelected(false);
                tvTime.setTextColor(getResources().getColor(R.color.A8f8f));
                tvFanwei.setTextColor(getResources().getColor(R.color.A8f8f));
            } else {
                //设置可以点击
                frmelayout.setEnabled(true);
                //显示能够打卡
                rlLayout.setVisibility(View.VISIBLE);
                frmelayout.setSelected(true);
                tvTime.setTextColor(getResources().getColor(R.color.bacck333));
                tvFanwei.setTextColor(getResources().getColor(R.color.bacck333));
            }
            llLayout.setSelected(false);
            imgLoading.setImageResource(R.drawable.icon_location_content);
            tvLonging.setTextColor(getResources().getColor(R.color.tv_grade));
            tvLonging.setText("你已在打卡范围内");
            tvCompany.setText(LoginCache.getInstance().getUserDetaileInfo().getCompany());
            tvCompany.setVisibility(View.VISIBLE);
            if (isclick) {
                llLayout.setSelected(true);
                prograssBar.setVisibility(View.VISIBLE);
                HashMap<String, String> map = signPamars();
                getPresenter().newStartSign(map);
                frmelayout.setEnabled(false);
                isclick = false;
            }
        } else {
            //不在打卡范围内，显示地图
            rlLayout.setVisibility(View.INVISIBLE);
            String latStr = signRange.getAddress().getLat();
            String lngStr = signRange.getAddress().getLng();
            double lat = Double.parseDouble(latStr);
            double lng = Double.parseDouble(lngStr);
            latitude2 = new LatLng(lat, lng);
            addMarkersToMap();

        }
    }

    @Override
    public void onFailed(String msg) {
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void onNowSignDataile(WillSignBean willSignBean) {
        this.willSignBean = willSignBean;
        if (null != willSignBean.getWorkTime()&&!TextUtils.isEmpty(willSignBean.getWorkTime())) {
            int signType = willSignBean.getSignType();
            if (1 == signType) {
                signTypes = "1";
                tvFanwei.setText("上班打卡");
                tvTishi.setText("请在" + willSignBean.getWorkTime() + "之前打卡");
            } else if (2 == signType) {
                signTypes = "2";
                tvFanwei.setText("下班打卡");
                tvTishi.setText("请在" + willSignBean.getWorkTime() + "之后打卡");
            } else {
                //没有
                isclick = false;
            }
        }else{
            tvFanwei.setText("");
            tvTishi.setText("");
            isclick = false;
        }
        if (!willSignBean.isCanSign()){
            ToastUtil.showToast(this, willSignBean.getMessage());
        }

    }

    @Override
    public void onUserSignState(SignStateBean signStateBean) {
        Log.i("test", "将要打卡的状态：" + signStateBean.toString());
        mMaterialDialog = new OptionMaterialDialog(this);
        int signStatusCode = signStateBean.getSignStatusCode();
        String mesg = "";
        if (2 == signStatusCode) {
            //迟到
            mesg = "迟到打卡,确定要打卡吗？";
            setDiolag(mesg);
        } else if (3 == signStatusCode) {
            //早退
            mesg = "早退打卡,确定要打卡吗？";
            setDiolag(mesg);
        } else if (1 == signStatusCode) {
            locationManager.locationStart(this);
            String stringToday = DateUtils.getStringToday(timeFormat);
            tvTime.setText(stringToday);
        }


    }

    public void setDiolag(String msg) {
        mMaterialDialog
                .setMessage(msg)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //再次开始定位
                        locationManager.locationStart(NewSignActivity.this);
                        mMaterialDialog.dismiss();

                    }
                })
                .setNegativeButton("取消",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mMaterialDialog.dismiss();
                            }
                        })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                //对话框消失后回调
                            }
                        }).show();

    }

    @Override
    public void onStartSign(SignNewReslut signReslut) {
        Log.i("test", "签到成功：" + signReslut.toString());
        if (signReslut.isResult()) {
            Intent intent = new Intent(NewSignActivity.this, NewSignSuccessActivity.class);
            intent.putExtra("signReslut", signReslut);
            startActivity(intent);
            finish();
        }else {
            frmelayout.setEnabled(true);
            prograssBar.setVisibility(View.INVISIBLE);
            llLayout.setSelected(false);
        }
    }

    @Override
    public void onSignFailed(String msg) {
        frmelayout.setEnabled(true);
        prograssBar.setVisibility(View.INVISIBLE);
        llLayout.setSelected(false);
        ToastUtil.showToast(this,msg);
    }


    @Override
    public View getInfoWindow(Marker marker) {

        View infoWindow = LayoutInflater.from(this).inflate(
                R.layout.custom_info_window, null);

        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        String stringToday = DateUtils.getStringToday(timeFormat);
        tvTime.setText(stringToday);
    }

    @NonNull
    @Override
    public NewSignPresenter createPresenter() {
        return new NewSignPresenter();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        destroyThread();
    }


    public static double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        Log.i("test", "再次开始定位");

        locationManager.locationStart(this);
        String stringToday = DateUtils.getStringToday(timeFormat);
        tvTime.setText(stringToday);
    }

    @Override
    public void deactivate() {

    }

    public class TimeThread extends Thread {
        @Override
        public void run() {
            super.run();
            do {
                try {
                    Thread.sleep(5000);
                    Message msg = new Message();
                    msg.what = msgKey1;
                    mHandler.sendMessage(msg);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case msgKey1:
                    String stringToday = DateUtils.getStringToday(timeFormat);
                    tvTime.setText(stringToday);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 销毁线程方法
     */
    private void destroyThread() {
        try {
            if (null != timeThread && Thread.State.RUNNABLE == timeThread .getState()) {
                try {
                    Thread.sleep(500);
                    timeThread .interrupt();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            timeThread = null;
        }
    }
}
